import {Component, OnInit} from '@angular/core';
import {Company} from '../../../../entity/company.model';
import {BladeContainerBase} from '../../../../shared/blade/blade-container-base';
import {CompanyService} from '../../../../service/company.service';
import {Observable} from 'rxjs/Observable';
import {List} from 'linqts';
import {TreeNode} from 'primeng/primeng';
import {BladeData} from '../../../../shared/blade/blade-data';
import {UserListComponent} from '../../user/user-list/user-list.component';
import {Command} from '../../../../shared/toolbar.service';
import {Blade} from '../../../../shared/blade/blade.model';
import {CompanyEditComponent} from '../company-edit/company-edit.component';
import {DialogResult} from '../../../../shared/dialog.service';

@Component({
  selector: 'app-company-list',
  templateUrl: './company-list.component.html',
  styleUrls: ['./company-list.component.css']
})
export class CompanyListComponent extends BladeContainerBase<Company> {

  private rootCompany: Company = new Company(0, 'Root', '', '', null, '', '', '', '', '', '', '');
  /**
   * 所有节点
   *
   * @type {TreeNode[]}
   * @memberof MenuListComponent
   */
  public files: TreeNode[] = [];
  public selectedFile: TreeNode[] = [];

  private companys: Company[] = [this.rootCompany];
  private currentCompany: Company;

  constructor(private companyService: CompanyService) {
    super();
    this.commands = [
      new Command('add', '添加', 'fa fa-plus', 'menu:insert', blade => this.exeAdd(blade), blade => this.canExeAdd(blade)),
      new Command('edit', '编辑', 'fa fa-edit', 'menu:update', blade => this.exeEdit(blade), blade => this.canExeEdit(blade)),
      new Command('delete', '删除', 'fa fa-trash-o', 'menu:delete', blade => this.exeDelete(blade), blade => this.canDelete(blade)),
    ];
  }

  exeAdd(blend: Blade): void {
    let data: BladeData = new BladeData();
    data.id = 'companyEdit';
    data.title = '组织结构创建';
    data.subtitle = '创建一个组织结构';
    data.isClosingDisabled = false;
    let createMenuBlade = this.bladeService.createBlade(CompanyEditComponent, data, true, null, {
      companys: this.companys,
      parent: this.currentEntity
    });
    this.bladeService.showBlade(createMenuBlade, this.currentBlade);
  }

  canExeAdd(blend: Blade): boolean {
    return true;
  }

  exeEdit(blend: Blade): void {
    if (this.currentEntity != undefined) {
      this.showMenuEditBlade(this.currentEntity)
    }
  }

  canExeEdit(blend?: Blade): boolean {
    return this.currentEntity != null;
  }

  exeDelete(blend: Blade): void {
    let selectedCompanys = this.getSelected();
    if (selectedCompanys.length > 0) {
      this.dialogService
        .showConfirmationDialog('确认删除', '是否要删除选中项？')
        .subscribe(dialogResult => {
          if (dialogResult == DialogResult.Ok) {
            this.currentBlade.bladeData.isLoading = true;

            this.companyService.batchDelete(selectedCompanys.map(o => o.companyId))
              .then(res => {
                if (res.code == '200') {
                  super.refresh(undefined);
                }
                if (res.code == '8001') {
                  this.dialogService
                    .showConfirmationDialog('删除失败', res.message);
                }
              })
              .catch(error => this.bladeData.error = error)
              .then(res => this.bladeData.isLoading = false);
          }
        })
    }
  }

  canDelete(blend: Blade): boolean {
    return this.getSelected().length > 0;
  }

  /**
   * 获得选中项
   */
  getSelected(): Company[] {
    if (this.companys.length > 0) {
      let filter = this.companys.filter(ref => ref.isChecked)
      return filter == null ? [] : filter;
    }
    return [];
  }

  public onNodeSelect(event: any) {
    let node: TreeNode = event.node;
    node.expanded = !node.expanded;
    let company = event.node.data;
    this.showUserListBlade(company);
  }

  /**
   * 展开编辑弹出层
   *
   */
  showMenuEditBlade(company: Company) {
    if (this.currentEntity != company
      || this.bladeService.findBlade('companyEditBlade') == undefined) {


      let data: BladeData = new BladeData();
      data.id = 'menuEditBlade';
      data.title = company.companyName + '编辑';
      data.subtitle = company.companyName;
      data.isClosingDisabled = false;
      let dicValueListBlade = this.bladeService.createBlade(CompanyEditComponent, data, false, company, {companys: this.companys});

      this.bladeService.showBlade(dicValueListBlade, this.currentBlade).then(res => {
        if (res) {
          this.currentEntity = company;
        }
      });
    }
  }

  /**
   * 单选
   */
  onItemCheack(event: HTMLInputElement, company: Company) {
    this.setChildrenChecked(company, event.checked);
    // this.setParenChecked(company);
  }

  /**
   * 设置子菜单是否选中
   */
  setChildrenChecked(company: Company, isChecked: boolean) {
    company.isChecked = isChecked;
    if (company.children && company.children.length) {
      company.children.forEach(childCompany => {
        this.setChildrenChecked(childCompany, isChecked);
      });
    }
  }

  /**
   * 设置父菜单是否选中
   *
   */
  setParenChecked(company: Company) {
    let parenCompany = this.companys.find(o => o.companyId == company.parentId);
    if (parenCompany != null) {
      let isCheckedCount = parenCompany.children.filter(o => o.isChecked).length;
      if (isCheckedCount == parenCompany.children.length) {
        parenCompany.isChecked = true;
      }
      else {
        parenCompany.isChecked = false;
      }
      this.setParenChecked(parenCompany);
    }
  }

  initData(): any | Observable<any> | Promise<any> {
    this.companyService.getComponys()
      .then(res => {
        if (!res) {
          return false
        }
        ;
        this.bladeData.isLoading = false;
        this.companys = [this.rootCompany];
        this.companys.push(...res);
        this.files = [];
        let level: number = 1;
        let firstCompanys = this.companys.filter(o => o.parentId == 0);
        if (firstCompanys != null) {
          firstCompanys = new List(firstCompanys).OrderBy(o => o.companyId).ToArray();
          firstCompanys.forEach(company => {
            company.companyLevel = level;
            let treeNode: TreeNode = {};
            treeNode.data = company;
            treeNode.expanded = true;
            this.files.push(treeNode);
            this.initChildMenu(company, treeNode);
          });

        }
        this.showUserListBlade(this.companys[1]);
      })
      .catch(err => {
        this.bladeData.error = err;
      });

  }

  initChildMenu(company: Company, treeNode: TreeNode) {
    let childrenCompanys = this.companys.filter(o => o.parentId == company.companyId);
    if (childrenCompanys != null && childrenCompanys.length > 0) {
      let level: number = company.companyLevel + 1;
      let list = new List(childrenCompanys);
      let childrenTemp = list.OrderBy(o => o.companyId).ToArray();
      company.children = childrenTemp;
      company.children.forEach(childrenCompany => {
        childrenCompany.companyLevel = level;
        let childernTreeNode: TreeNode = {};
        childernTreeNode.data = childrenCompany;
        childernTreeNode.expanded = true;
        if (!treeNode.children) {
          treeNode.children = [];
        }
        treeNode.children.push(childernTreeNode);
        //递归
        this.initChildMenu(childrenCompany, childernTreeNode);
      });
    }
  }


  showUserListBlade(selectCompany: Company) {
    let currCompanys = [...this.companys];
    currCompanys.shift();
    this.currentEntity = selectCompany;
    this.currentBlade.bladeService.closeChildrenBlade;
    let data: BladeData = new BladeData();
    data.id = 'UserList';
    data.title = selectCompany.companyName + '用户列表';
    data.subtitle = '用户列表';
    data.isClosingDisabled = false;
    let permissionListBlade = this.bladeService.createBlade(UserListComponent, data, false, null, {
      company: selectCompany,
      companys: currCompanys
    });
    this.bladeService.showBlade(permissionListBlade, this.currentBlade)
  }
}


// WEBPACK FOOTER //
// ./src/app/module/basic/company/company-list/company-list.component.ts
